package com.eco.fanliapp.job.dtkitemjob;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.service.HDKUtils;
import com.eco.fanliapp.service.IAppGoodsService;
import com.eco.fanliapp.service.IUserCashschemeService;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.vo.respone.DTKResponse;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取大淘客更新商品
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DTKNewestGoodsTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(DTKNewestGoodsTask.class);

    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private IAppGoodsService appGoodsService;

    public DTKNewestGoodsTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执行大淘客商品更新定时任务-DTKItemTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        long startTime = System.currentTimeMillis();
        AppCompany com = userCashschemeService.findCompanyAll();
        List<AppGoods> updateAppGoodsList = new ArrayList<>();
        String pageId = "1";
        String pageSize = "200";
        while (true) {
            try {
                String result = daTaoKeItemInfoService.getNewestGoods(pageSize, pageId);
                Integer code = JSONObject.parseObject(result).getInteger("code");
                if (code != 0) {
                    break;
                }
                result = JSONObject.parseObject(result).getString("data");
                String pageid = JSONObject.parseObject(result).getString("pageId");
                JSONArray array = JSONArray.parseArray(JSONObject.parseObject(result).getString("list"));
                List<DTKResponse.DataBean> dtkResponse = JsonUtils.getJsonToList(array.toJSONString(), DTKResponse.DataBean.class);
                if (dtkResponse == null || dtkResponse.size() <= 0) {
                    break;
                }

                for (DTKResponse.DataBean dataBean : dtkResponse) {
                    AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(dataBean.getGoodsId());
                    if (appGoods != null) {
                        AppGoods appGoodsNew = new AppGoods();
                        AppGoods goods = HDKUtils.getUpdateAppGoodsFromDTK(dataBean, appGoodsNew);
//                        goods.setTableId(appGoods.getTableId());
//                        goods.setAddUserId(-114);
                        goods = iAppGoodsService.getMoneyInfoByGoodsId(com, goods);
                        //判断是否最终金额小于0
                        BigDecimal itemendprice = new BigDecimal(goods.getItemendprice() == null ? 0d : goods.getItemendprice());
                        BigDecimal tkMoney = new BigDecimal(goods.getTkmoney() == null ? "0" : goods.getTkmoney());
                        if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                            continue;
                        }
                        appGoods.setUpdateTime(DateUtils.getNowTimestamp());
                        //根据商品id查询商品是否存在
                        Integer num = appGoodsMapper.selectAppGoodsByAddUserId(goods.getItemid());
                        if (num > 0) {
                            continue;
                        }
                        try {
                            if (!StringUtils.isEmpty(appGoods.getCouponnum()) && !StringUtils.isEmpty(dataBean.getCouponReceiveNum())) {
                                goods.setCouponsurplus(String.valueOf(Integer.valueOf(appGoods.getCouponnum()) - Integer.valueOf(dataBean.getCouponReceiveNum())));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.info("优惠券数量转换异常");
                        }
                        String goodsTkMoney = goods.getTkmoney() == null ? "0" : goods.getTkmoney();
                        Double goodsItemendprice = goods.getItemendprice() == null ? 0d : goods.getItemendprice();
                        String goodsItemprice = goods.getItemprice() == null ? "0" : goods.getItemprice();
                        String goodsCouponendtime = goods.getCouponendtime() == null ? "0" : goods.getCouponendtime();
                        String goodsCouponstarttime = goods.getCouponstarttime() == null ? "0" : goods.getCouponstarttime();
                        if (goods.getCouponmoney() != appGoods.getCouponmoney() || !goodsItemprice.equals(appGoods.getItemprice())
                                || !goodsItemendprice.equals(appGoods.getItemendprice()) || !goodsTkMoney.equals(appGoods.getTkmoney())
                                || !goodsCouponendtime.equals(appGoods.getCouponendtime()) || !goodsCouponstarttime.equals(appGoods.getCouponstarttime())) {

                            appGoods.setCouponmoney(goods.getCouponmoney());
                            appGoods.setItemendprice(goodsItemendprice);
                            appGoods.setItemprice(goodsItemprice);
                            appGoods.setCouponstarttime(goodsCouponstarttime);
                            appGoods.setCouponendtime(goodsCouponendtime);
                            appGoods.setTkmoney(goodsTkMoney);
                            updateAppGoodsList.add(appGoods);
                        }

                    }
                }
                if (updateAppGoodsList.size() > 0 && updateAppGoodsList.size() > 200) {
                    try {
                        boolean i = appGoodsService.updateBatchById(updateAppGoodsList);
                        if (i) {
                            log.info("更新大淘客商品   入库商品更新成功 数据size={} ", updateAppGoodsList.size());
                            updateAppGoodsList.clear();
                        } else {
                            log.info("更新大淘客商品   入库商品更新失败 数据={} ", updateAppGoodsList.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                pageId = pageid;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取大淘客更新商品错误");
                break;
            }
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行获取大淘客更新商品定时任务任务-DTKItemTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }
}
